Add Two Distances (in inch-feet) System Using Structures in C Program

07-11-17 Course- C

This program takes two distances in inch-feet system and stores in data members of two structure variables. Then, this program calculates the sum of two distances and displays it.

Source code to add two distance using structure


#include <stdio.h>
struct Distance{
    int feet;
    float inch;
}d1,d2,sum;
int main(){
    printf("Enter information for 1st distance\n");
    printf("Enter feet: ");
    scanf("%d",&d1.feet);
    printf("Enter inch: ");
    scanf("%f",&d1.inch);
    printf("\nEnter information for 2nd distance\n");
    printf("Enter feet: ");
    scanf("%d",&d2.feet);
    printf("Enter inch: ");
    scanf("%f",&d2.inch);
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;

/* If inch is greater than 12, changing it to feet. */
    if (sum.inch>12.0)
    {
        sum.inch=sum.inch-12.0;
        ++sum.feet;
    }
    printf("\nSum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
    return 0;
}

Output


Enter information for 1st distance
Enter feet: 12
Enter inch: 3.45

Enter information for 1st distance
Enter feet: 12
Enter inch: 9.2

Sum of distances=25'-0.6"

In this program, a structure Distance is defined with inch and feet as its members. Then, three variables(d1, d2 and sum) of struct Distance type is created. Two variables(d1 and d2) are used for taking distance from user and the sum of two distance is stored in variable sum and then, displayed.